Crate count_instructions
source ·Expand description
Counts the instructions executed within a single function.
When developing constant-time code, it can be helpful to validate that several executions of a given function have the same number of instructions, and that the same instructions were used.
The approach used by this crate is to single-step the function using the operating system debug API, optionally recording the address of each instruction. This is currently implemented only for Linux; for other operating systems, it will fail with an error.
Using the debug API to single-step the function has several drawbacks:
- It can be very slow, especially when not compiled in release mode;
- It cannot be used while another debugger is attached to the process;
- Its use might be restricted by several system hardening mechanisms.
On the other hand, using the debug API has the advantage of tracing the real code executed by the CPU, as generated by the compiler, instead of symbolic execution of the source code, or emulation on another architecture.
Examples
use count_instructions::count_instructions;
fn add(left: usize, right: usize) -> usize {
left + right
}
let mut count = 0;
let result = count_instructions(|| add(2, 2), |instruction| count += 1)?;
assert_eq!(result, 4);
assert_ne!(count, 0);
For a stronger test, you can store and later compare the instruction addresses:
use count_instructions::count_instructions;
fn add(left: usize, right: usize) -> usize {
left + right
}
let mut addresses = Vec::new();
let result = count_instructions(
|| add(2, 2),
|instruction| addresses.push(instruction.address())
)?;
assert_eq!(result, 4);
assert!(!addresses.is_empty());
Note that, due to monomorphization and inlining, a separate monomorphic function must be used whenever the instruction addresses from more than one execution will be compared later:
use count_instructions::count_instructions;
use count_instructions::Address;
fn add(left: usize, right: usize) -> usize {
left + right
}
#[inline(never)]
fn count(left: usize, right: usize, capacity: usize) -> std::io::Result<Vec<Address>> {
let mut addresses = Vec::with_capacity(capacity);
let result = count_instructions(
|| add(left, right),
|instruction| addresses.push(instruction.address())
)?;
assert_eq!(result, 4);
Ok(addresses)
}
let expected = count(2, 2, 0)?;
let addresses = count(3, 1, expected.len())?;
assert_eq!(addresses, expected);
Structs
- Information about an instruction executed by the function being traced.
Functions
- Runs the function being tested, calling a counter function for each instruction executed.
Type Definitions
- Represents the address of a machine instruction.